package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smedi.ismedi.progress.api.dto.request.AttachmentRequest;
import com.smedi.ismedi.progress.core.domain.repository.AttachmentRepository;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.AttachmentEntity;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.AttachmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 用来处理附件的入库与查询
 */
@Service
public class AttachmentImpl implements AttachmentRepository {
    @Autowired
    private AttachmentMapper attachmentMapper;

   private static final QueryWrapper<AttachmentEntity> delete = new QueryWrapper<>();
    /**
     *  保持附件
     * @param tableName 主表名
     * @param key 关联key
     * @param attachmentEntities 附件
     */
    @Override
    public void save(String tableName, Long key, List<AttachmentRequest> attachmentEntities) {
        if(attachmentEntities==null) return;
        // 构建附件与主表的关联关系
        List<AttachmentEntity> attach = AttachmentEntity.getAttach(tableName,key,attachmentEntities);
        // 先执行删除绑定的附件信息
        delete.clear();
        delete.eq("relevance_key",key);
        attachmentMapper.delete(delete);
        // 重新绑定附件信息
        attach.forEach(v->{
            attachmentMapper.insert(v);
        });
    }

    /**
     * 获取附件信息
     * @param tableName 主表名
     * @param key 关联key
     * @return 附件列表
     */
    @Override
    public List<AttachmentEntity> getAttach(String tableName, Long key) {
        QueryWrapper<AttachmentEntity> query = new QueryWrapper<>();
        query.eq("table_name",tableName).eq("relevance_key",key);
        return  attachmentMapper.selectList(query);
    }
}
